package com.bzchao.texttospeech;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import android.widget.Toast;

import java.util.List;
import java.util.Locale;

/**
 * Created by sonseongbin on 2017. 3. 19..
 */

public class TTS {
    private final String TAG = TTS.class.getSimpleName();
    private final String ENGINE = "com.iflytek.speechsuite";

    private TextToSpeech textToSpeech;

    public TTS(Context context, Locale locale) {
        TextToSpeech.OnInitListener onInitListener = getOnInitListener(locale);
        textToSpeech = new TextToSpeech(context, onInitListener, ENGINE);
        TextToSpeech.EngineInfo engineInfo = getEngine(textToSpeech, ENGINE);
        if (engineInfo == null) {
            Toast.makeText(context, "未安装讯飞语音引擎", Toast.LENGTH_SHORT).show();
            return;
        }
        UtteranceProgressListener progressListener = getUtteranceProgressListener();
        textToSpeech.setOnUtteranceProgressListener(progressListener);
    }

    private TextToSpeech.OnInitListener getOnInitListener(Locale locale) {
        return status -> {
            Log.i(TAG, "onInit:" + status);
            if (status != TextToSpeech.ERROR) {
                textToSpeech.setLanguage(locale);
            }
        };
    }

    private UtteranceProgressListener getUtteranceProgressListener() {
        return new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {
                Log.d(TAG, "onStart / utteranceID = " + utteranceId);
            }

            @Override
            public void onDone(String utteranceId) {
                Log.d(TAG, "onDone / utteranceID = " + utteranceId);
            }

            @Override
            public void onError(String utteranceId) {
                Log.d(TAG, "onError / utteranceID = " + utteranceId);
            }
        };
    }

    public TextToSpeech.EngineInfo getEngine(TextToSpeech textToSpeech, String engine) {
        List<TextToSpeech.EngineInfo> engines = textToSpeech.getEngines();
        for (TextToSpeech.EngineInfo engineInfo : engines) {
            if (engine.equals(engineInfo.name)) {
                return engineInfo;
            }
        }
        return null;
    }

    public void speak(String text) {
        if (textToSpeech != null) {
            String myUtteranceID = "myUtteranceID";
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, myUtteranceID);
        }
    }

    public void stop() {
        textToSpeech.stop();
    }

    public void shutdown() {
        textToSpeech.shutdown();
    }

    public boolean isSpeaking() {
        return textToSpeech.isSpeaking();
    }

}
